<?php

namespace Largezhou\Admin;

use App\Models\Menu;
use Closure;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
use Largezhou\Admin\Form\Form;
use Largezhou\Admin\Layout\Content;
use Largezhou\Admin\Table\Table;

class Admin
{
    /**
     * @param Model $model
     *
     * @return \Largezhou\Admin\Form\Form
     */
    public function form(Model $model = null)
    {
        return new Form($model);
    }

    /**
     * @param string|Model $model
     *
     * @return \Largezhou\Admin\Table\Table
     */
    public function table($model)
    {
        return new Table($this->getModel($model));
    }

    /**
     * 获取模型实例
     *
     * @param string|Model $model
     *
     * @return mixed
     */
    public function getModel($model)
    {
        if ($model instanceof Model) {
            return $model;
        }

        if (is_string($model) && class_exists($model)) {
            return $this->getModel(new $model());
        }

        throw new InvalidArgumentException("{$model}不是一个有效的模型");
    }

    /**
     * @param Closure|null $builder
     *
     * @return \Largezhou\Admin\Layout\Content
     */
    public function content(Closure $builder = null)
    {
        return new Content($builder);
    }

    /**
     * 加载菜单到配置中
     */
    public function loadMenus()
    {
        config(['admin.menus' => Menu::makeTreeOptions()]);
    }

    /**
     * 从admin的配置中,加载某些配置到系统配置中
     */
    public function loadConfigs()
    {
        config(['filesystems.disks.admin_upload_driver' => config('admin.upload_driver')]);
    }
}
